﻿@page "/devicepointmanager"

@using IotClientApp.Client.Pages.Dialog;
@using IotClientApp.Shared
@using IotClientApp.Shared.Enums;
@using Microsoft.AspNetCore.SignalR.Client
@using Newtonsoft.Json
@using PluginInterface;
@using System.Net.Http.Headers;
@inject IDialogService DialogService
@inject HttpClient Http
@inject ISnackbar Snackbar
@inject IJSRuntime js

<MudGrid>
<MudItem xs="12" md="2">
        <MudList Clickable="true" @bind-SelectedItem="selectedItem" @bind-SelectedValue="selectDeviceId">
            <MudListSubheader>
                设备
                <MudChip Color="Color.Secondary">
                    @(selectedItem?.Text ?? "You are dry") (@(selectDeviceId?.ToString() ?? "0"))
                </MudChip>
            </MudListSubheader>
            @foreach (var Device in Devices)
            {
                <MudListItem Text="@Device.Name" Value="@Device.Id" OnClick="async()=>{
await OpenPoint();
}" Icon="@Icons.Material.Filled.Drafts" />
            }
        </MudList>
 </MudItem>
 <MudItem xs="12" md="10">

<MudButton Variant="Variant.Filled" StartIcon="@Icons.Material.Filled.Save" IconColor="Color.Secondary" Size="Size.Large" OnClick="@(async() => {
await AddPoint();
})">新增</MudButton>
&nbsp;
<MudButton Variant="Variant.Filled" StartIcon="@Icons.Material.Filled.Save" IconColor="Color.Secondary" Size="Size.Large" OnClick="@(async() => {
await DownLoadData();
})">导出</MudButton>
&nbsp;

<MudButton Variant="Variant.Filled" StartIcon="@Icons.Material.Filled.Save" IconColor="Color.Secondary" Size="Size.Large" OnClick="@(async() => {
await UploadFileDialog();
})">上传</MudButton>
&nbsp;
<MudButton Variant="Variant.Filled" StartIcon="@Icons.Material.Filled.Save" IconColor="Color.Secondary" Size="Size.Large" OnClick="@(async() => {
await LoadData(pageIndex);
})">刷新</MudButton>


<MudTable Items="@messages" Breakpoint="Breakpoint.Sm" LoadingProgressColor="Color.Info">
    <ToolBarContent>
        <MudText Typo="Typo.h6">Periodic Elements</MudText>
        <MudSpacer />
        <MudTextField T="string" ValueChanged="@(s=>OnSearch(s))" Placeholder="Search" Adornment="Adornment.Start"
                      AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Medium" Class="mt-0"></MudTextField>
    </ToolBarContent>
    <HeaderContent>
                <MudTh><MudTableSortLabel SortLabel="sign_field" T="DeviceParamModel">名称</MudTableSortLabel></MudTh>
                <MudTh><MudTableSortLabel SortLabel="sign_field" T="DeviceParamModel">地址</MudTableSortLabel></MudTh>
                <MudTh><MudTableSortLabel SortLabel="nr_field" T="DeviceParamModel">类型</MudTableSortLabel></MudTh>
                <MudTh><MudTableSortLabel SortLabel="nr_field" T="DeviceParamModel">大小端</MudTableSortLabel></MudTh>
                <MudTh><MudTableSortLabel SortLabel="nr_field" T="DeviceParamModel">读写</MudTableSortLabel></MudTh>
                <MudTh><MudTableSortLabel SortLabel="name_field" T="DeviceParamModel">原值</MudTableSortLabel></MudTh>
                <MudTh><MudTableSortLabel SortLabel="name_field" T="DeviceParamModel">值</MudTableSortLabel></MudTh>
                <MudTh><MudTableSortLabel SortLabel="name_field" T="DeviceParamModel">状态</MudTableSortLabel></MudTh>
                <MudTh><MudTableSortLabel SortLabel="name_field" T="DeviceParamModel">表达式</MudTableSortLabel></MudTh>
                <MudTh><MudTableSortLabel SortLabel="position_field" T="DeviceParamModel">更新时间</MudTableSortLabel></MudTh>
                <MudTh><MudTableSortLabel SortLabel="position_field" T="DeviceParamModel">创建时间</MudTableSortLabel></MudTh>
                <MudTh><MudTableSortLabel SortLabel="position_field" T="DeviceParamModel">描述</MudTableSortLabel></MudTh>
                <MudTh><MudTableSortLabel SortLabel="position_field" T="DeviceParamModel">操作</MudTableSortLabel></MudTh>
    </HeaderContent>
    <RowTemplate>
                <MudTd DataLabel="Nr">@context.Name</MudTd>
                <MudTd DataLabel="Sign">@context.Address</MudTd>
                <MudTd DataLabel="Sign">@context.DataTypeName</MudTd>
                <MudTd DataLabel="Sign">@context.EndianTypeName</MudTd>
                <MudTd DataLabel="Sign">@context.ReadWrite</MudTd>
                <MudTd DataLabel="Name">@context.Value</MudTd>
                <MudTd DataLabel="Name">@context.CookedValue</MudTd>
                <MudTd DataLabel="Name">@context.StatusType</MudTd>
                <MudTd DataLabel="Name">@context.Expressions</MudTd>
                <MudTd DataLabel="Name">@context.Timestamp.ToString("yyyy-MM-dd HH:mm:ss")</MudTd>
                <MudTd DataLabel="Position">@context.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")</MudTd>
                <MudTd DataLabel="Name">@context.Desc</MudTd>
            <MudTd>
            <MudButton Variant="Variant.Filled" StartIcon="@Icons.Material.Filled.Save" IconColor="Color.Secondary" Size="Size.Small" OnClick="@(async() => {
                await EditPoint(context);
            })">编辑</MudButton>
            <MudButton Variant="Variant.Filled" StartIcon="@Icons.Material.Filled.Delete" IconColor="Color.Secondary" Size="Size.Small" OnClick="@(() => {
                DelPoint(context);
            })">删除</MudButton>
        </MudTd>
    </RowTemplate>
    <NoRecordsContent>
        <MudText>No matching records found</MudText>
    </NoRecordsContent>
    <LoadingContent>
        <MudText>Loading...</MudText>
    </LoadingContent>
    <PagerContent>
        <MudPagination SelectedChanged="PageChanged" Count="@pageCount" Class="pa-4" />
    </PagerContent>
</MudTable>
</MudItem>
</MudGrid>

@code {

    private HashSet<DeviceConfigInfoModel> selectedItems = new HashSet<DeviceConfigInfoModel>();
    private List<DeviceInfoModel> Devices = new List<DeviceInfoModel>();
    private object selectDeviceId;
    MudListItem selectedItem;
    private string selectDeviceName = "";

    Color _color = Color.Primary;
    private HubConnection? hubConnection;
    private List<DeviceParamModel> messages = new List<DeviceParamModel>();
    private int pageSize = 10;
    private int pageIndex = 1;
    private int pageCount = 0;

    protected override async Task OnInitializedAsync()
    {
        await LoadDeviceData();
        if (Devices != null && Devices.Count() > 0)
        {
            await LoadData(pageIndex);
        }
    }
    private async Task OpenPoint()
    {
        pageIndex = 1;
        await LoadData(pageIndex);
    }
    private async Task LoadDeviceData()
    {
        var response = await Http.PostAsJsonAsync("api/Device/GetDeviceInfos", new GetDeviceInfoModel
        {
        });
        if (response.IsSuccessStatusCode)
        {
            var responseContent = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseContent);
            try
            {
                var result = JsonConvert.DeserializeObject<PageResponse<DeviceInfoModel>>(responseContent);
                if (result != null)
                {
                    if (result.Data.Count() > 0)
                    {
                        selectDeviceId = result.Data.First().Id;
                        selectDeviceName = result.Data.First().Name;
                        Console.WriteLine(selectDeviceName);
                    }
                    Devices = result.Data;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
    private async void PageChanged(int i)
    {
        await LoadData(i);
    }

    private async Task DownLoadData()
    {
        var response = await Http.PostAsJsonAsync<GetDeviceParamModel>("api/Param/DownloadIoTDevicePhyList", new GetDeviceParamModel
            {
                DeviceId = selectDeviceId.ToString()
            });
        if (response.IsSuccessStatusCode)
        {
            var excelBytes = await response.Content.ReadAsByteArrayAsync();
            await js.InvokeVoidAsync("saveAsFile", $"参数{DateTime.Now.ToString("yyyyMMddHHmmss")}.xls", Convert.ToBase64String(excelBytes));
        }
    }
    private async Task LoadData(int pageIndex)
    {
        this.pageIndex = pageIndex;
        var response = await Http.PostAsJsonAsync<GetDeviceParamModel>("api/Param/GetDeviceParams", new GetDeviceParamModel
            {
                DeviceId = selectDeviceId.ToString(),
                PageIndex = pageIndex,
                PageSize = pageSize
            });
        if (response.IsSuccessStatusCode)
        {
            var responseContent = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseContent);
            try
            {
                var result = JsonConvert.DeserializeObject<PageResponse<DeviceParamModel>>(responseContent);
                messages = result.Data;
                pageCount = (int)Math.Ceiling(result.PageCount * 1.0 / pageSize);
                StateHasChanged();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
    private void OnSearch(string text)
    {
        //searchString = text;
        //table.ReloadServerData();
    }
    private void DelPoint(DeviceParamModel context)
    {

    }
    private async Task UploadFileDialog()
    {
        var parameters = new DialogParameters<UploadFilePoint_Dialog> { { x => x.DeviceId, selectDeviceId.ToString() } };
        var dialog = await DialogService.ShowAsync<UploadFilePoint_Dialog>("上传参数", parameters);
        var result = await dialog.Result;

        if (!result.Canceled)
        {
            Console.WriteLine("ok");
            await LoadData(pageIndex);
        }
    }
    private async Task AddPoint()
    {
        var parameters = new DialogParameters<PointSave_Dialog> { { x => x.pointInfo, new DeviceParamModel { DeviceId = selectDeviceId.ToString() } }, { x => x.Title, "新增" } };
        var dialog = await DialogService.ShowAsync<PointSave_Dialog>("新增", parameters);
        var result = await dialog.Result;

        if (!result.Canceled)
        {
            Console.WriteLine("ok");
            await LoadData(pageIndex);
        }
    }
    private async Task EditPoint(DeviceParamModel pointInfo)
    {
        var parameters = new DialogParameters<PointSave_Dialog> { { x => x.pointInfo, pointInfo }, { x => x.Title, "编辑" } };
        var dialog = await DialogService.ShowAsync<PointSave_Dialog>("编辑", parameters);
        var result = await dialog.Result;

        if (!result.Canceled)
        {
            Console.WriteLine("ok");
            await LoadData(pageIndex);
        }

        Console.WriteLine($"{pointInfo.Name}");
    }
}